<?php

namespace app\shop\controller\api;

use app\ApiController;
use app\channel\model\ChannelGoodsModel;
use app\member\model\AccountModel;
use think\facade\Cache;
use think\Db;

use app\shop\model\OrderModel;
use app\mainadmin\model\PaymentModel;
use app\mainadmin\model\TaskingModel;
use app\mainadmin\model\TaskingLogModel;

/*------------------------------------------------------ */
//-- 订单相关API
/*------------------------------------------------------ */

class Order extends ApiController
{
    /*------------------------------------------------------ */
    //-- 优先执行
    /*------------------------------------------------------ */
    public function initialize()
    {
        parent::initialize();
        $this->checkLogin();//验证登陆
        $this->Model = new OrderModel();
    }
    /*------------------------------------------------------ */
    //-- 获取列表
    /*------------------------------------------------------ */
    public function getList()
    {
        $p = input("p/d", 1);

        $where[] = ['o.order_type', 'in', [0, 1]];
        $where[] = ['o.user_id', '=', $this->userInfo['user_id']];
        $where[] = ['o.is_split', 'in', [0, 1]];
        $where[] = ['o.is_del', '=', 0];
        $where[] = ['o.is_status', '=', 1];
        $type = input('type', '', 'trim');
        $isSaleAfter = true;
        $isWaitShipping = false;
        switch ($type) {
            case 'waitPay':
                $where[] = ['o.is_pay', '>', 0];
                $where[] = ['o.order_status', '=', '0'];
                $where[] = ['o.pay_status', '=', '0'];
                $where[] = ['og.after_sale_num', '=', 0];
                $isSaleAfter = false;
                break;
            case 'waitShipping':
                $where[] = ['o.order_status', '=', '1'];
                $where[] = ['o.shipping_status', '=', '0'];
                //$where['and'][] = "(pay_status = 1 OR is_pay = 0)";
                $isWaitShipping = true;
                $where[] = ['og.after_sale_num', '=', 0];
                $isSaleAfter = false;
                break;
            case 'waitSign':
                $where[] = ['o.order_status', '=', '1'];
                $where[] = ['o.shipping_status', '=', '1'];
                $where[] = ['og.after_sale_num', '=', 0];
                $isSaleAfter = false;
                break;
            case 'sign':
                $where[] = ['o.order_status', '=', '1'];
                $where[] = ['o.shipping_status', '=', '2'];
                $where[] = ['og.after_sale_num', '=', 0];
                $isSaleAfter = false;
                break;
            default:
                break;
        }

        $orderData = Db::table('shop_order_info')->alias('o')
            ->leftJoin('shop_order_goods og', 'o.order_id = og.order_id')
            ->where($where);
        if ($isWaitShipping) {
            $orderData = $orderData->where(function ($query) {
                $query->where('o.pay_status', 1)->whereOr('o.is_pay', 0);
            });
        }
        $orderData = $orderData->field('o.order_id')
            ->group('o.order_id')
            ->order('order_id DESC')
            //->fetchSql(true)
            ->paginate(5, false, ['page' => $p]);

        $orderData = $orderData->toArray();
        $data = [
            'list' => $orderData['data'],
            'page' => $orderData['current_page'],
            'total_count' => $orderData['total'],
            'page_count' => $orderData['last_page'],
            'page_size' => $orderData['per_page']
        ];

        //$data = $this->getPageList($this->Model, $where, 'order_id', 5);
        $config = config('config.');
        $list = [];
        foreach ($data['list'] as $key => $order) {
            $orderInfo = $this->Model->info($order['order_id'], $config, $isSaleAfter);
            if (!empty($orderInfo)) {
                $list[] = $orderInfo;
            }
        }
        $data['list'] = $list;
        return $this->success($data);
    }
    /*------------------------------------------------------ */
    //-- 获取订单详细
    /*------------------------------------------------------ */
    public function getOrderStats()
    {
        $data['orderStats'] = $this->Model->userOrderStats($this->userInfo['user_id']);
        return $this->success($data);
    }
    /*------------------------------------------------------ */
    //-- 获取订单详细
    /*------------------------------------------------------ */
    public function info()
    {
        $order_id = input('order_id', 0, 'intval');
        if ($order_id < 1) return $this->error('传参错误.');
        $orderInfo = $this->Model->info($order_id);
        if ($orderInfo['user_id'] != $this->userInfo['user_id']) return $this->error('无权访问.');
        $ChannelGoodsModel = new ChannelGoodsModel();
        foreach ($orderInfo['goodsList'] as $key => $val) {
            $check = $ChannelGoodsModel->where('goods_id', $val['goods_id'])->find();
            if (empty($check)) { // 非云仓
                $orderInfo['goodsList'][$key]['isAfterSale'] = true;
            } else { // 云仓
//                $orderInfo['goodsList'][$key]['isAfterSale'] = false;
                $orderInfo['goodsList'][$key]['isAfterSale'] = true;
            }
        }
        return $this->success($orderInfo);
    }
    /*------------------------------------------------------ */
    //-- 获取待支付订单
    /*------------------------------------------------------ */
    public function getPayOrder()
    {
        $order_id = input('order_id', 0, 'intval');
        if ($order_id < 1) {
            return $this->error('订单ID传值错误.');
        }
        $orderInfo = $this->Model->info($order_id);

        if ($orderInfo['is_pay'] == 0) {
            return $this->error('当前订单不能进行支付操作.');
        }
        $data['order_id'] = $orderInfo['order_id'];
        $data['order_amount'] = $orderInfo['order_amount'];
        $data['order_sn'] = $orderInfo['order_sn'];
        $data['is_stock'] = 1;
        $settings = settings();
        $platform = input('platform', '', 'trim');
        $payList = (new PaymentModel)->getRows($platform);
        //获取用户余额
        $account_where['user_id'] = $orderInfo['user_id'];
        $users_account = Db::name('users_account')->where($account_where)->field('balance_money')->find();
        if ($data['order_amount'] > $users_account['balance_money']) {
            $data['is_user_account'] = 0;
        } else {
            $data['is_user_account'] = 1;
        }
        $data['payList'] = [];
        $isOffLinePay = 0;
        foreach ($payList as $pay) {
            if ($pay['is_buy_pay'] == 0) {
                continue;
            }
            $_pay['money'] = -1;
            if ($pay['pay_code'] == 'offline') {
                continue;
//                $isOffLinePay = 1;  //隐藏线下支付
            } elseif ($pay['pay_code'] == 'balance') {
                $_pay['money'] = $this->userInfo['account']['balance_money'];
            }
            $_pay['pay_id'] = $pay['pay_id'];
            $_pay['pay_code'] = $pay['pay_code'];
            $_pay['pay_name'] = $pay['pay_name'];
            $data['payList'][] = $_pay;
        }

        if ($isOffLinePay == 1) {
            $data['offline']['is_sys'] = 1;
            $data['offline']['weixin_usd'] = empty($settings['receive_weixin_qrcode']) ? 0 : 1;
            $data['offline']['alipay_usd'] = empty($settings['receive_alipay_qrcode']) ? 0 : 1;
            $data['offline']['bank_usd'] = empty($settings['receive_bank_name']) ? 0 : 1;
            if ($data['offline']['weixin_usd'] == 1) {
                $data['offline']['is_usd'] = 1;
                $data['offline']['weixin_qrcode'] = $settings['receive_weixin_qrcode'];
                $data['offline']['weixin_name'] = $settings['receive_weixin_name'];
                $data['offline']['weixin_account'] = $settings['receive_weixin_account'];
            }
            if ($data['offline']['alipay_usd'] == 1) {
                $data['offline']['is_usd'] = 1;
                $data['offline']['alipay_qrcode'] = $settings['receive_alipay_qrcode'];
                $data['offline']['alipay_name'] = $settings['receive_alipay_name'];
                $data['offline']['alipay_account'] = $settings['receive_alipay_account'];
            }
            if ($data['offline']['bank_usd'] == 1) {
                $data['offline']['is_usd'] = 1;
                $data['offline']['bank_name'] = $settings['receive_bank_name'];
                $data['offline']['bank_subbranch'] = $settings['receive_bank_subbranch'];
                $data['offline']['bank_user_name'] = $settings['receive_bank_user_name'];
                $data['offline']['bank_card_number'] = $settings['receive_bank_card_number'];
            }
        }
        return $this->success($data);
    }
    /*------------------------------------------------------ */
    //-- 执行订单操作
    /*------------------------------------------------------ */
    public function action()
    {
        $order_id = input('order_id', 0, 'intval');
        $mkey = 'OrderIng_' . $order_id;
        $status = Cache::get($mkey);
        if (empty($status) == false) {
            return $this->error('请求失败');
        }
        Cache::set($mkey, 1, 30);
        $type = input('type', '', 'trim');
        $config = config('config.');
        $upData['order_id'] = $order_id;
        switch ($type) {
            case 'cancel'://取消
                $upData['order_status'] = $config['OS_CANCELED'];
                $upData['cancel_time'] = time();
                $_log = '用户取消订单';
                break;
            case 'sign'://签收
                $upData['shipping_status'] = $config['SS_SIGN'];
                $upData['sign_time'] = time();
                $_log = '用户签收订单';
                break;
            case 'del'://删除
                $upData['is_del'] = 1;
                $_log = '用户删除订单';
                break;
            default:
                return $this->error('没有相关操作.');
                break;
        }
        $orderInfo1 = $this->Model->info($order_id);
        Db::startTrans();//开启事务
        if ($type == "sign") {
            $taskingLogModel = new TaskingLogModel();
            $taskingModel = new TaskingModel();
            $tasking_info = $taskingModel->where('id', 3)->find();
            if ($tasking_info['status'] == 1) {
                $count_tasking = $taskingLogModel->where("tasking_id={$tasking_info['id']} and user_id={$orderInfo1['user_id']}")->count();
                if ($taskingLogModel->where("status!=1 and tasking_id={$tasking_info['id']} and user_id={$orderInfo1['user_id']}")->find()) {
//                if (!$taskingLogModel->where("status!=1 and tasking_id={$tasking_info['id']} and user_id={$orderInfo1['user_id']}")->update(['status'=>1])) {
                    $where_s[] = ['status', '<>', 1];
                    $where_s[] = ['tasking_id', '=', $tasking_info['id']];
                    $where_s[] = ['user_id', '=', $orderInfo1['user_id']];
                    if (!Db::name('main_tasking_log')->where($where_s)->update(['status' => 1])) {
                        Db::rollback(); //回滚事务
                        return $this->error('签收失败.');
                    }
                } else {
                    if (($tasking_info['type'] != 1 || ($tasking_info['type'] == 2 && $tasking_info['task_nums'] < $count_tasking)) && !$taskingLogModel->insert(['user_id' => $orderInfo1['user_id'], 'tasking_id' => $tasking_info['id'], 'status' => 1, 'createtime' => time()])) {
                        Db::rollback(); //回滚事务
                        return $this->error('签收失败.');
                    }
                }
                if ($tasking_info['type'] != 1 || ($tasking_info['type'] == 2 && $tasking_info['task_nums'] < $count_tasking)) {
                    $userinfo_account = Db::name('users_account')->where('user_id', $orderInfo1['user_id'])->find();

//                    if (!Db::name('users_account')->where('user_id', $orderInfo1['user_id'])->udpate(['use_integral' => $userinfo_account['use_integral'] + $tasking_info['points']])) {
                    if (!Db::name('users_account')->where('user_id', $orderInfo1['user_id'])->setInc('use_integral', $tasking_info['points'])) {
                        Db::rollback();
                        return '任务积分更新失败.';
                    }
                }
            }



            //判断是否需要给用户分销奖
            $distribution_amount = Db::name('shop_order_goods')->where(array('order_id' => $order_id, 'after_sale_num' => 0, 'return_goods_number' => 0))->sum('distribution_amount');
            if ($distribution_amount > 0) {
                $AccountModel = new AccountModel();
                // 直接打款
                $AccountModel->change([
                    'total_dividend' => $distribution_amount,
                    'balance_money' => $distribution_amount,
                    'change_type' => 4,
                    'change_desc' => '分销奖',
                    'by_id' => $order_id
                ], $this->userInfo['pid']);
                //更新分销日志状态
                Db::name('distribution_dividend_log')->where(array('order_id' => $order_id, 'status' => 1))->update(array('status' => 9, 'update_time' => time()));
            }

            #判断是否需要给代理商结算(逻辑修改：普通用户和VIP从代理走货时，需要用户确认收货后，才把订单金额返到代理的钱包)
            $users_account = Db::name('users_account_log')->where(array('order_id' => $order_id, 'change_type' => 1, 'status' => 0))->find();
            if ($users_account) {
                $users_account['balance_money'] = $users_account['balance_money']-$users_account['shipping_fee'];
                //更新日志状态
                Db::name('users_account_log')->where(array('log_id' => $users_account['log_id']))->update(array('status' => 1, 'update_time' => time()));
                //解冻
                Db::name('users_account')->where(array('user_id' => $users_account['user_id']))->setDec('frozen_money', $users_account['balance_money']);
                //增加容易
                Db::name('users_account')->where(array('user_id' => $users_account['user_id']))->setInc('balance_money', $users_account['balance_money']);
            }


        }
        $res = $this->Model->upInfo($upData);
        if ($res !== true) {
            Db::rollback(); //回滚事务
            return $this->error($res);
        }
        Db::commit();//提交事务
        Cache::rm($mkey);
        $orderInfo = $this->Model->info($order_id);
        $this->Model->_log($orderInfo, $_log);
        return $this->success();
    }


    /*------------------------------------------------------ */
    //-- 提交支付凭证
    /*------------------------------------------------------ */
    public function postOffLinePay()
    {
        $order_id = input('order_id', 0, 'intval');
        if ($order_id < 1) {
            return $this->error('﻿订单ID传值错误.');
        }
        $fileList = input('fileList', '', 'trim');
        if (empty($fileList)) {
            return $this->error('请上传付款凭证.');
        }
        $orderInfo = $this->Model->info($order_id);
        if ($orderInfo['isPay'] == 0) {
            return $this->error('当前订单不能进行支付操作.');
        }

        if ($orderInfo['is_stock'] == 0) {
            return $this->error('未进行库存处理订单，不能完成操作.');
        }
        $file_path = config('config._upload_') . 'offline_pay/' . date('m');
        $offlineimg = [];
        $fileList = explode(',', $fileList);
        foreach ($fileList as $file) {
            $offlineimg[] = copyFile($file, $file_path);
        }
        $payList = (new PaymentModel)->getRows(true, 'pay_code');
        if (empty($payList['offline'])) {
            return $this->error('支付方式错误，请重试.');
        }

        Db::startTrans();//开启事务
        $upData['is_pay'] = 2;
        $upData['pay_id'] = $payList['offline']['pay_id'];
        $upData['pay_code'] = $payList['offline']['pay_code'];
        $upData['pay_name'] = $payList['offline']['pay_name'];
        $upData['offlineimg'] = join(',', $offlineimg);
        $upData['order_id'] = $order_id;
        $upData['pay_status'] = config('config.PS_WAITCHACK');
        $upData['pay_time'] = time();
        $res = $this->Model->upInfo($upData);
        if ($res == false) {
            foreach ($offlineimg as $img) {
                @unlink('.' . $img);
            }
            Db::rollback();// 回滚事务
            return $this->error('更新订单失败.');
        }
        $res = $this->Model->_log($orderInfo, '提交支付凭证.');
        if ($res < 1) {
            Db::rollback();// 回滚事务
            return '订单日志写入失败，请重试.';
        }
        Db::commit();//提交事务
        foreach ($fileList as $file) {
            @unlink('.' . $file);
        }
        return $this->success();
    }


}
